package com.server.web.controller.officialAccounts;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.server.common.core.domain.AjaxResult;
import com.server.common.utils.SysThreadPool;
import com.server.common.utils.upload.UploadFile;
import com.server.common.utils.wx.WechatUtil;
import com.server.pinggu.domain.*;
import com.server.pinggu.dto.AddFormsValsDTO;
import com.server.pinggu.dto.FormsUploadImageDTO;
import com.server.pinggu.dto.PageValue;
import com.server.pinggu.service.*;
import com.server.pinggu.service.impl.SenFormsServiceImpl;
import com.server.pinggu.vo.SenFormsVo;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Classname FengRui
 * @Description 评估信息
 * @Date 2022-11-15 15:17
 */
@RestController
@RequestMapping("/officialAccounts/Forms")
@RequiredArgsConstructor
@Slf4j
public class SenFormsInfoController {
    private final Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");//这个也行

    private final ISenFormsService iSenFormsService;

    private final ISenUserService iSenUserService;

    private final ISenUserdataService iSenUserdataService;

    private final ISenPgyService iSenPgyService;

    private final ISenActionlogService iSenActionlogService;

    private final ISenFormsRemarkService iSenFormsRemarkService;

    private final ISenFormvalsService iSenFormvalsService;

    private final SysThreadPool sysThreadPool;

    private final StringRedisTemplate stringRedisTemplate;

    @GetMapping("/tiaozhuan")
    public void test(HttpServletResponse response,@RequestParam("code") String code ,@RequestParam("state") String state) throws Exception{
        log.info("code:{},state:{}",code,state);
        JSONObject accessTokenOauth2 = WechatUtil.getAccessTokenOauth2(code);
        if (StringUtils.isNotEmpty(accessTokenOauth2.getString("errcode"))){
            response.sendRedirect(WechatUtil.TUrl+state+"?openId="+null);
            return;
        }
        log.info("获取的accToken:{}",JSONObject.toJSONString(accessTokenOauth2));
        if (CollectionUtil.isNotEmpty(accessTokenOauth2)){
            String openid = accessTokenOauth2.getString("openid");
            synchronizingUserInformation(accessTokenOauth2.getString("access_token"),openid);
            String testUrl =  WechatUtil.TUrl+state+"?openId="+openid;
            response.sendRedirect(testUrl);
        }
    }

    public void synchronizingUserInformation(String accessToken,String openId){
        JSONObject userInfo = WechatUtil.getUserInfo(accessToken, openId);
        log.info("用户信息：{}", JSONObject.toJSONString(userInfo));
        stringRedisTemplate.opsForValue().set(openId+"_USERINFO",JSONObject.toJSONString(userInfo));
        stringRedisTemplate.opsForValue().set(openId+"ACCTOKEN",accessToken);
        if (StringUtils.isNotEmpty(userInfo.getString("errcode"))){
            return;
        }
        if (CollectionUtil.isNotEmpty(userInfo)){
            String nickname = userInfo.getString("nickname");
            String headimgurl = userInfo.getString("headimgurl");
            String openid = userInfo.getString("openid");
            String city = userInfo.getString("city");
            String country = userInfo.getString("country");
            SenUser one = iSenUserService.getOne(new LambdaUpdateWrapper<SenUser>().eq(SenUser::getOopenid,openId));
            if (one == null){
                SenUser senUser = new SenUser();
                senUser.setOopenid(openid);
                senUser.setDttime(System.currentTimeMillis()/1000L);
                iSenUserService.save(senUser);
                iSenUserService.update(new LambdaUpdateWrapper<SenUser>().eq(SenUser::getId,senUser.getId()).set(SenUser::getUsername,"hr"+senUser.getId()));
                SenUserdata senUserdata = new SenUserdata();
                senUserdata.setRealname(EmojiParser.parseToAliases(nickname));
                senUserdata.setRealnamebase64(new String(Base64Utils.encode(nickname.getBytes())));
                senUserdata.setHeadimgurl(headimgurl);
                senUserdata.setCity(city);
                senUserdata.setTrade(" ");
                senUserdata.setCountry(country);
                senUserdata.setId(senUser.getId());
                senUserdata.setAds(" ");
                iSenUserdataService.insert(senUserdata);
            }else{
                SenUserdata senUserdata = new SenUserdata();
                senUserdata.setRealname(EmojiParser.parseToAliases(nickname));
                senUserdata.setRealnamebase64(new String(Base64Utils.encode(nickname.getBytes())));
                senUserdata.setHeadimgurl(headimgurl);
                senUserdata.setCity(city);
                senUserdata.setCountry(country);
                senUserdata.setId(one.getId());
                iSenUserdataService.updateById(senUserdata);
            }
        }
    }

    @ApiOperation(value = "根据openId获取评估列表")
    @PostMapping("getformsListByOpenId/{openId}")
    public AjaxResult getformsInfoByOpenId(@PathVariable("openId") String openId, @RequestBody SenFormsVo senForms){
        if (StringUtils.isEmpty(openId)){
            throw new RuntimeException("openId can not be empty");
        }
        log.info("openid:{}",openId);
        Integer sqsjFront = null;
        Integer sqsjBack = null;
        if (senForms!=null){
            sqsjBack = senForms.getSqsjBack();
            sqsjFront = senForms.getSqsjFront();
        }
        SenUser one = iSenUserService.getOne(new LambdaUpdateWrapper<SenUser>().eq(SenUser::getOopenid,openId));
        if (one!=null) {
            SenUserdata byId = iSenUserdataService.getById(one.getId());
            if (byId == null  || (byId.getIsLuru() == 0 && byId.getIsAdmin() == 0 && byId.getPgyid() == 0)){
                return AjaxResult.success(new ArrayList<>());
            }
            if (byId.getIsLuru() != 1 &&  byId.getIsAdmin() !=1) {
                senForms.setPinguid(one.getId()+"");
            }
        }else{
            return AjaxResult.success(new ArrayList<>());
        }
        senForms.setPageNum((senForms.getPageNum()-1)*senForms.getPageSize());
        PageValue list = iSenUserService.queryList2(senForms,sqsjFront,sqsjBack,senForms.getPageNum(),senForms.getPageSize(),senForms.getStatusStr());
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "备注")
    @RequestMapping("addRemark/{openId}")
    public AjaxResult addRemark(@PathVariable("openId")String openId, @RequestBody SenFormsRemark senFormsRemark){
        if (StringUtils.isEmpty(openId)){
            throw new RuntimeException("openId can not be empty");
        }
        SenUser one = iSenUserService.getOne(new LambdaUpdateWrapper<SenUser>().eq(SenUser::getOopenid,openId));
        if (null==one){
            return AjaxResult.error();
        }
        senFormsRemark.setCtype(1);
        senFormsRemark.setDttime(new Date());
        senFormsRemark.setUserid(one.getId());
        iSenFormsRemarkService.save(senFormsRemark);
        return AjaxResult.success();
    }

    @ApiOperation(value = "取消申请")
    @RequestMapping("cancelApplication/{openId}")
    public AjaxResult getformsInfoByOpenId(@PathVariable("openId")String openId,@RequestParam("formsId") Long formsId,@RequestParam("cancelreason")String remark){
        if (StringUtils.isEmpty(openId)){
            throw new RuntimeException("openId can not be empty");
        }
        if (formsId == null){
            return AjaxResult.error();
        }
        SenUser one = iSenUserService.getOne(new LambdaUpdateWrapper<SenUser>().eq(SenUser::getOopenid,openId));
        String username = one.getUsername();
        iSenActionlogService.save(new SenActionlog(null,one.getId(),username,formsId,"取消申请",new Date(System.currentTimeMillis()),null));
        iSenFormsService.update(new LambdaUpdateWrapper<SenForms>().set(SenForms::getStatus,2).set(SenForms::getCanceltime,System.currentTimeMillis()/1000).set(SenForms::getCancelreason,remark).set(SenForms::getCanceluid,one.getId()).eq(SenForms::getId,formsId));
        return AjaxResult.success();
    }

    @ApiOperation(value = "根据formsId和openId 获取评估单详情和评估员信息")
    @GetMapping("getformsInfoById/{openId}")
    public AjaxResult getformsInfoById(@PathVariable("openId") String openId,@RequestParam("id")Long Id){
        if (StringUtils.isEmpty(openId)){
            throw new RuntimeException("openId can not be empty");
        }
        Map<String,Object> map  = new HashedMap();
        SenForms byId = iSenFormsService.getById(Id);
        SenFormsServiceImpl.setImage(byId);
        map.put("senForms",byId);
        if (StringUtils.isNotEmpty(byId.getPinguid())) {
            SenUser one = iSenUserService.getOne(new LambdaQueryWrapper<SenUser>().eq(SenUser::getOopenid, openId));
            if (one!=null){
                String username = one.getUsername();
                SenUserdata userDate = iSenUserdataService.getById(one.getId());
                if(userDate!=null){
                    map.put("userId",userDate.getId());
                    if ( userDate.getPgyid()!=null) {
                        SenPgy p = iSenPgyService.getById(userDate.getPgyid());
                        if(p!=null){
                            username = p.getXm();
                        }
                    }
                }
                iSenActionlogService.save(new SenActionlog(null,one.getId(),username,Id,"打开受理单",new Date(System.currentTimeMillis()),null));
            }
            List<String> pingList = Arrays.asList(byId.getPinguid().split(","));
            String[] split = byId.getPingname().split(",");
            List<SenUserdata> list = iSenUserdataService.list(new LambdaUpdateWrapper<SenUserdata>().in(SenUserdata::getId, pingList));
            if (CollectionUtil.isNotEmpty(list)){
                List<Integer> collect = list.stream().map(SenUserdata::getPgyid).distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect)){
                    List<SenPgy> pgy = iSenPgyService.list(new LambdaQueryWrapper<SenPgy>().in(SenPgy::getId, collect));
                    if(ArrayUtil.isNotEmpty(split)){
                        for (SenPgy senPgy : pgy) {
                            if (split[0].equals(senPgy.getXm())){
                                map.put("pgy0",senPgy);
                                break;
                            }
                        }
                    }
                    if(ArrayUtil.isNotEmpty(split)&& split.length>=2){
                        for (SenPgy senPgy : pgy) {
                            if (split[1].equals(senPgy.getXm())){
                                map.put("pgy1",senPgy);
                                break;
                            }
                        }
                    }
                }
            }
        }
        return AjaxResult.success(map);
    }

    @ApiOperation(value = "提交A")
    @GetMapping("submitA/{openId}")
    public AjaxResult submitA(@RequestParam("formsId")Long id,@PathVariable("openId") String openId){
        if (StringUtils.isEmpty(openId)){
            throw new RuntimeException("openId can not be empty");
        }
        SenUser one = iSenUserService.getOne(new LambdaQueryWrapper<SenUser>().eq(SenUser::getOopenid, openId));
        if (one!=null){
            String username = one.getUsername();
            SenUserdata userDate = iSenUserdataService.getById(one.getId());
            if (userDate!=null && userDate.getPgyid()!=null) {
                SenPgy p = iSenPgyService.getById(userDate.getPgyid());
                if(p!=null){
                    username = p.getXm();
                }
            }
            iSenActionlogService.save(new SenActionlog(null,one.getId(),username,id,"提交-A",new Date(System.currentTimeMillis()),null));
            iSenFormsService.update(new LambdaUpdateWrapper<SenForms>().set(SenForms::getLasteditUid,userDate.getId()).eq(SenForms::getId,id));
        }
        return AjaxResult.success();
    }



    @ApiOperation(value = "提交B")
    @GetMapping("submitB/{openId}")
    public AjaxResult submitB(@RequestParam("formsId")Long id,@PathVariable("openId") String openId){
        if (StringUtils.isEmpty(openId)){
            throw new RuntimeException("openId can not be empty");
        }
        SenUser one = iSenUserService.getOne(new LambdaQueryWrapper<SenUser>().eq(SenUser::getOopenid, openId));
        if (one!=null){
            String username = one.getUsername();
            SenUserdata userDate = iSenUserdataService.getById(one.getId());
            if (userDate!=null && userDate.getPgyid()!=null) {
                SenPgy p = iSenPgyService.getById(userDate.getPgyid());
                if(p!=null){
                    username = p.getXm();
                }
            }
            iSenActionlogService.save(new SenActionlog(null,one.getId(),username,id,"提交-B",new Date(System.currentTimeMillis()),null));
            iSenFormsService.update(new LambdaUpdateWrapper<SenForms>().set(SenForms::getLasteditUid,userDate.getId()).eq(SenForms::getId,id));
        }
        return AjaxResult.success();
    }

    @ApiOperation(value = "提交录入")
    @PostMapping("addFormsVals/{openId}")
    public AjaxResult addFormsVals(@RequestBody AddFormsValsDTO addFormsValsDTO,@PathVariable("openId") String openId){
        if (StringUtils.isEmpty(openId)){
            throw new RuntimeException("openId can not be empty");
        }
        if (addFormsValsDTO== null || addFormsValsDTO.getFormsId() == null ||CollectionUtil.isEmpty(addFormsValsDTO.getList())){
            return AjaxResult.error();
        }
        List<Long> collect = addFormsValsDTO.getList().stream().map(SenFormvals::getFieldid).distinct().collect(Collectors.toList()).stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(collect)){
            LambdaQueryWrapper<SenFormvals> delete = new LambdaQueryWrapper<>();
            delete.eq(SenFormvals::getFormid,addFormsValsDTO.getFormsId());
            delete.in(SenFormvals::getFieldid,collect);
            iSenFormvalsService.remove(delete);
        }
        SenUser one = iSenUserService.getOne(new LambdaQueryWrapper<SenUser>().eq(SenUser::getOopenid, openId));
        String username = one.getUsername();

        List<SenFormvals> insert = addFormsValsDTO.getList().stream().filter(a -> StringUtils.isNotEmpty(a.getVal())).collect(Collectors.toList());
        iSenFormvalsService.saveList(insert);

        iSenActionlogService.save(new SenActionlog(null,one.getId(),username,addFormsValsDTO.getFormsId(),"保存-B",new Date(System.currentTimeMillis()),null));
        return AjaxResult.success();
    }
    @ApiOperation(value = "保存录入")
    @PostMapping("addFormsValsNew/{openId}")
    public AjaxResult addFormsValsNew(@RequestBody AddFormsValsDTO addFormsValsDTO,@PathVariable("openId") String openId,@RequestParam("str")String Str){
        if (StringUtils.isEmpty(openId)){
            throw new RuntimeException("openId can not be empty");
        }
        if (addFormsValsDTO== null || addFormsValsDTO.getFormsId() == null ||CollectionUtil.isEmpty(addFormsValsDTO.getList())){
            return AjaxResult.error();
        }
        List<Long> collect = addFormsValsDTO.getList().stream().map(SenFormvals::getFieldid).distinct().collect(Collectors.toList()).stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(collect)){
            LambdaQueryWrapper<SenFormvals> delete = new LambdaQueryWrapper<>();
            delete.eq(SenFormvals::getFormid,addFormsValsDTO.getFormsId());
            delete.in(SenFormvals::getFieldid,collect);
            iSenFormvalsService.remove(delete);
        }
        SenUser one = iSenUserService.getOne(new LambdaQueryWrapper<SenUser>().eq(SenUser::getOopenid, openId));
        String username = one.getUsername();
        List<SenFormvals> insert = addFormsValsDTO.getList().stream().filter(a -> StringUtils.isNotEmpty(a.getVal())).collect(Collectors.toList());
        iSenFormvalsService.saveList(insert);
        iSenActionlogService.save(new SenActionlog(null,one.getId(),username,addFormsValsDTO.getFormsId(),Str,new Date(System.currentTimeMillis()),null));
        return AjaxResult.success();
    }

    private final List<Long> ids = new ArrayList<Long>(){{
        add(12451L);
        add(12452L);
        add(12038L);
        add(12039L);
        add(12100L);
        add(12101L);
        add(12431L);
        add(12441L);
        add(12443L);
        //add(11689L);
        add(12439L);
        add(11697L);
    }};


    @ApiOperation(value = "根据formsId和openId 获取评估单详情和评估员信息")
    @GetMapping("getformsParticularsById")
    public AjaxResult getformsInfoById(@RequestParam("id") Long Id){
        Map<String,Object> map  = new HashedMap();
        SenForms byId = iSenFormsService.getById(Id);
        SenFormsServiceImpl.setImage(byId);
        map.put("senForms",byId);
        if (byId!=null) {
            //获取评估表单内容
            List<SenFormvals> list = iSenFormvalsService.listValue(byId.getId());
            list.sort(Comparator.comparing(SenFormvals::getFieldid).reversed());
            if (CollectionUtil.isNotEmpty(list)){
                Map<String,Object> value = new HashedMap();
                for (SenFormvals senFormvals : list) {
                    if (senFormvals.getVtype() == 1) {
                        //判断是否返回数组格式 ids 里面得为数组ID
                            if (ids.contains(senFormvals.getFieldid())){
                                String[] split = senFormvals.getVal().split("\\{s}");
                                value.put("F"+senFormvals.getFieldid(), Arrays.stream(split).mapToInt(Integer::parseInt).toArray());
                            }else{
                                value.put("F"+senFormvals.getFieldid(),senFormvals.getVal());
                            }
                    }else{
                        if (ids.contains(senFormvals.getFieldid())){
                            String[] split = senFormvals.getVal().split("\\{s}");
                            value.put("F"+senFormvals.getFieldid(), Arrays.stream(split).mapToInt(Integer::parseInt).toArray());
                        }else{
                            if (isNumeric(senFormvals.getVal())) {
                                value.put("F"+senFormvals.getFieldid(),Long.valueOf(senFormvals.getVal().trim()));
                            }else{
                                value.put("F"+senFormvals.getFieldid(),senFormvals.getVal());
                            }
                        }
                    }
                }
                map.put("collect",value);
            }else{
                map.put("collect",null);
            }
            String[] split = byId.getPinguid().split(",");
            String[] pingnames = byId.getPingname().split(",");
            if (ArrayUtil.isNotEmpty(split) &&ArrayUtil.isNotEmpty(pingnames)){
                if (split.length>=1){
                    String ybbsm = iSenUserdataService.selectYbbsmById(split[0]);
                    if (StringUtils.isNotEmpty(ybbsm)){
                        map.put("pgy1",ybbsm+"-"+pingnames[0]);
                    }
                }
                if (split.length>=2){
                    String ybbsm = iSenUserdataService.selectYbbsmById(split[1]);
                    if (StringUtils.isNotEmpty(ybbsm)){
                        map.put("pgy2",ybbsm+"-"+pingnames[1]);
                    }
                }
            }
        }
        return AjaxResult.success(map);
    }

    public boolean isNumeric(String str) {
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    @PostMapping("updateFormsInfo")
    public AjaxResult updateFormsInfo(@RequestBody SenForms senForms){
        if(null == senForms){
            return AjaxResult.error();
        }
        iSenFormsService.updateById(senForms);
        return AjaxResult.success();
    }

    @PostMapping("uploadImage")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile multipartFile){
        String url = UploadFile.uploadFile(multipartFile);
        if (StringUtils.isEmpty(url)){
            return AjaxResult.error();
        }
        return AjaxResult.success(url);
    }

    @PostMapping("updateImage")
    public AjaxResult uploadImage(@RequestBody FormsUploadImageDTO formsUploadImageDTO){
        if (null!=formsUploadImageDTO&& formsUploadImageDTO.getId()!=null) {
            if (StringUtils.isEmpty(formsUploadImageDTO.getImage1())&&
                    StringUtils.isEmpty(formsUploadImageDTO.getImage2())&&
                    StringUtils.isEmpty(formsUploadImageDTO.getImage3())&&
                    StringUtils.isEmpty(formsUploadImageDTO.getImage4())&&
                    StringUtils.isEmpty(formsUploadImageDTO.getImage5())&&
                    StringUtils.isEmpty(formsUploadImageDTO.getImage6())
            ){
                return AjaxResult.error();
            }
            SenForms byId = iSenFormsService.getById(formsUploadImageDTO.getId());
            LambdaUpdateWrapper<SenForms> lambdaUpdateWrapper  = new LambdaUpdateWrapper();
            lambdaUpdateWrapper.eq(SenForms::getId,formsUploadImageDTO.getId());
            if (byId!=null && byId.getPgdate()==null){
                lambdaUpdateWrapper.eq(SenForms::getPgdate, DateUtil.format(new Date(),"yyyyMMdd"));
            }
            if (StringUtils.isNotEmpty(formsUploadImageDTO.getImage1())){
                lambdaUpdateWrapper.set(SenForms::getImage1,formsUploadImageDTO.getImage1());
            }
            if (StringUtils.isNotEmpty(formsUploadImageDTO.getImage2())){
                lambdaUpdateWrapper.set(SenForms::getImage2,formsUploadImageDTO.getImage2());
            }
            if (StringUtils.isNotEmpty(formsUploadImageDTO.getImage3())){
                lambdaUpdateWrapper.set(SenForms::getImage3,formsUploadImageDTO.getImage3());
            }
            if (StringUtils.isNotEmpty(formsUploadImageDTO.getImage4())){
                lambdaUpdateWrapper.set(SenForms::getImage4,formsUploadImageDTO.getImage4());
            }
            if (StringUtils.isNotEmpty(formsUploadImageDTO.getImage5())){
                lambdaUpdateWrapper.set(SenForms::getImage5,formsUploadImageDTO.getImage5());
            }
            if (StringUtils.isNotEmpty(formsUploadImageDTO.getImage6())){
                lambdaUpdateWrapper.set(SenForms::getImage6,formsUploadImageDTO.getImage6());
            }
            iSenFormsService.update(lambdaUpdateWrapper);

        }
        return AjaxResult.success();
    }
}
